package com.jbp.intercepter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.exception.RRException;
import com.jbp.model.User;
import com.jbp.redis.RedisConfigService;
import com.jbp.service.BlackDeviceService;
import com.jbp.service.BlackIpService;
import com.jbp.service.UserService;
import com.jbp.utils.Constant;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class RequestLogIntercepter implements HandlerInterceptor {



    @Autowired
    private RedisConfigService redisConfigService;

    @Autowired
    private UserService userService;

    @Autowired
    private BlackIpService blackIpService;

    @Autowired
    private BlackDeviceService blackDeviceService;

    /***
     * 登陆拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        System.out.println("URI:"+request.getRequestURI());
        //从header中获取token
        String token = request.getHeader("token");
        String sessionId = request.getHeader("sessionId");
        //如果header中不存在token，则从参数中获取token
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        if (StringUtils.isBlank(sessionId)) {
            sessionId = request.getParameter("sessionId");
        }
        //token为空
        if (StringUtils.isBlank(token)) {
            throw new RRException("请重新登录", 210);
        }
        if (StringUtils.isBlank(sessionId)) {
            throw new RRException("请重新登录", 210);
        }
        //根据token获取 userId
        Object seesionId= redisConfigService.get(token);
        if (seesionId == null){
            throw new RRException("登录失效，请重新登录",210);
        }
        if (!seesionId.equals(sessionId)){
            throw new RRException("登录失效，请重新登录",210);
        }
        User user= userService.getOne(new QueryWrapper<User>().eq("code",token));
        if (user==null){
            throw new RRException("登录失效，请重新登录",210);
        }

        if(user.getDel()==1 || blackDeviceService.isBlack(user.getDevice()) || blackIpService.isBlack(user.getIp())) {
            throw new RRException("账号冻结中", 210);
        }

        //判断用户是否在线
        redisConfigService.set(Constant.ROOM_PREFIX+user.getId(),"online", Constant.ONLINE_TIME);

        //将设为在线
        if ("offline".equalsIgnoreCase(user.getIsOnline())) {
            user.setIsOnline("online");
            userService.updateById(user);
        }

        request.setAttribute(Constant.USER_ID, user.getId());
        return true;
    }
}
